'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 钻石一键升满繁荣度
 * @author sundbcn@gmail.com (sun debing)
 */

var async = require('async');
var Code = require('../../../../consts/code');
var moduleType = require('../../../../consts/moduleType');
var operationType = require('../../../../consts/operationType');
var rewardService = require('../../../../services/rewardService');
var roleService = require('../../../../services/roleService');
var PlayerManager = require('../../../../libs/playerManager');
var constantUtil = require('../../../../util/constantUtil');

module.exports = function (msg, session, next) {
    var role_id = session.uid;

    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(['role', 'accrued'], cb);
            },
            function (cb) {
                var role_model = player_manager.role;

                if (role_model.prosperous >= 100) {
                    // 繁荣度已满，不需提升
                    return next(null, {
                        code: Code.BATTLE_FULL_PROSPEROUS
                    });
                }
                var add_prosperous = 100 - role_model.prosperous;
                var need_diamond = add_prosperous * constantUtil.value('prosperous_recover_point');

                // 扣除钻石
                if (!roleService.subDiamond(player_manager, moduleType.MDL_PVP, operationType.OPR_PVP_INC_FULL_PROSPEROUS_BUY_DIAMOND, need_diamond)) {
                    return next(null, {
                        code: Code.USER_DIAMOND_NOT_ENOUGH
                    });
                }

                // 设置保护，并提升繁荣度
                role_model.setProtectProsperous(add_prosperous);

                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK
            });
        }
    );
};
